package com.zp.self.module.level_1_问道.XI_多线程.AQS;


import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author By ZengPeng
 * @Description Semaphore是用来保护一个或者多个共享资源的访问，Semaphore内部维护了一个计数器，其值为可以访问的共享资源的个数。
 * 一个线程要访问共享资源，先获得信号量，如
 * 果信号量的计数器值大于1，意味着有共享资源可以访问，则使其计数器值减去1，再访问共享资源。
 * @date in  2021/3/5 17:34
 * @Modified By
 */
public class Semaphore分析 {

    private AtomicInteger number = new AtomicInteger(100);
    @Test
    //读取100次
    public void  test() throws InterruptedException {
        Semaphore sp = new Semaphore(0);
        sp.release(1);
        CountDownLatch cd = new CountDownLatch(1);
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 100; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    //获取
                    try {
                        sp.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(number.get()<=1){
                        cd.countDown();
                        return;
                    }
                    System.out.println("线程："+Thread.currentThread().getName()+"!   当前值："+number.get());
                    number.getAndDecrement();
                    //释放
                    sp.release();
                }
            });
        }
        cd.await();
        System.out.println("执行完毕！");


    }
}
